import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt

url1="http://lishi.tianqi.com/shiyan/202502.html"
url2="http://lishi.tianqi.com/shiyan/202503.html"
headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0'}

def get_page(url):
    res=requests.get(url,headers=headers)
    html=res.content.decode('utf-8')
    # print(html)
    bs=BeautifulSoup(html,"html.parser")
    lis=bs.body.find('ul',{"class":"thrui"}).find_all('li')
    r=[]
    for li in lis:
        divs = li.find_all('div')
        date=divs[0].string.strip()
        temp_high=divs[1].string.replace("℃","")
        temp_low = divs[2].string.replace("℃", "")
        weather=divs[3].string
        wind=divs[4].string
        r.append([date,temp_high,temp_low,weather,wind])
    return r


def data_proc(wdata):
    df=pd.DataFrame(wdata,columns=["日期星期","最高气温","最低气温","天气","风力"])
    df=df.drop_duplicates()
    df=df.assign(日期=df['日期星期'].str.slice(0,10),星期=df['日期星期'].str.slice(11,14))
    df['最高气温']=df['最高气温'].astype(int)
    df['最低气温'] = df['最低气温'].astype(int)
    df['平均气温']=(df['最高气温']+df['最低气温'])/2
    df=df.assign(风力级别=df['风力'].map(lambda x:"".join(list(filter(str.isdigit,x)))))
    df['风力级别']=df['风力级别'].astype(int)
    return df

# data1=data_proc(get_page(url1))
# data1.to_csv('202502天气.csv')
# data2=data_proc(get_page(url2))
# data2.to_csv('202503天气.csv')
# print(get_page(url1))

df1=pd.read_csv('202502天气.csv')
df2=pd.read_csv('202503天气.csv')
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["axes.unicode_minus"]=False
#每日气温
plt.plot(df1['日期'],df1['平均气温'],label='平均气温')
plt.plot(df1['日期'],df1['最高气温'],label='最高气温')
plt.plot(df1['日期'],df1['最低气温'],label='最低气温')
plt.legend()
plt.title("2025年2月每日气温")
plt.xticks(rotation=30)
plt.show()

plt.plot(df2['日期'],df2['平均气温'],label='平均气温')
plt.plot(df2['日期'],df2['最高气温'],label='最高气温')
plt.plot(df2['日期'],df2['最低气温'],label='最低气温')
plt.legend()
plt.title("2025年3月每日气温")
plt.xticks(rotation=30)
plt.show()

# 平均气温3-5风力<5的天数
c1=len(df1.query("(平均气温>=3) and (平均气温<=5) and (风力级别)<5"))
c2=len(df2.query("(平均气温>=3) and (平均气温<=5) and (风力级别)<5"))
plt.bar(['2月','3月'],[c1,c2],width=0.5)
plt.title('2025年2-3月宜居天数')
plt.ylabel("天")
plt.show()
# 各种天气的数量
weather=set()
weather.update(df1['天气'])
weather.update(df2['天气'])
wlist1=[]
for w in weather:
    c=0
    for x in df1['天气']:
        if w==x:
            c+=1
    wlist1.append(c)

wlist2=[]
for w in weather:
    c=0
    for x in df2['天气']:
        if w==x:
            c+=1
    wlist2.append(c)

plt.bar([x-0.2 for x in range(len(weather))],wlist1,width=0.4,label='2月')
plt.bar([x+0.2 for x in range(len(weather))],wlist2,width=0.4,label='3月')
plt.xticks(range(len(weather)),list(weather))
plt.legend()
plt.title('2025年2-3月各类天气天数')
plt.show()
